#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File  :get_jingdong_cookies.py
# Time  :广州总公司-广州子公司-2025/1/14 16:42
# Email :fortunatedong@163.com
# Author:by Adonli
import base64
import time

import cv2

import json

from jingdong_order_synchronization_kuaipu_zhuzhanghao.settings.logger import Loggings
logs = Loggings()

class jingdong_login():
    def __init__(self,pw):
        self.browser = pw.chromium.launch(headless=False, channel="chrome")
        self.context = self.browser.new_context()
        self.page = self.context.new_page()
    # @retry_on_exception(max_retries=3,delay=2)


    def calculate_slide_distance(self,bg_path, slider_path):
        # 读取图片
        # bg_img = cv2.imread(bg_path)
        # small_img = cv2.imread(slider_path)

        bg_img = cv2.imread(bg_path)
        tp_img = cv2.imread(slider_path)  # 读取到两个图片，进行灰值化处理
        bg_gray = cv2.cvtColor(bg_img, cv2.COLOR_BGR2GRAY)
        bg_gray = cv2.GaussianBlur(bg_gray, (5, 5), 0)
        bg_edge = cv2.Canny(bg_gray, 30, 100)
        rgb_bg_gray = cv2.cvtColor(bg_edge, cv2.COLOR_GRAY2RGB)

        sd_gray = cv2.cvtColor(tp_img, cv2.COLOR_BGR2GRAY)
        sd_gray = cv2.GaussianBlur(sd_gray, (5, 5), 0)
        sd_edge = cv2.Canny(sd_gray, 30, 100)
        rgb_sd_gray = cv2.cvtColor(sd_edge, cv2.COLOR_GRAY2RGB)
        result = cv2.matchTemplate(rgb_bg_gray, rgb_sd_gray, cv2.TM_CCORR_NORMED)
        _, _, _, max_loc = cv2.minMaxLoc(result)
        cv2.rectangle(bg_img, (max_loc[0], max_loc[1]), (max_loc[0] + 50, max_loc[1] + 50),
                      (0, 255, 0), 2)

        cv2.imwrite("../jingdong_order_synchronization_kuaipu_zhuzhanghao/img/bg_img.png", bg_img)
        # cv2.imshow("bg_img", bg_img)
        # cv2.imshow("bg_gray", bg_gray)
        # cv2.imshow("sd_gray", sd_gray)
        # cv2.imshow("rgb_sd_gray", rgb_sd_gray)
        # cv2.imshow('result', result)
        distance = max_loc[0] + 4
        # print(distance)
        return distance

    def get_track(self,distance):
        # 移动轨迹
        track = []
        # 当前位移
        current = 0
        # 减速阈值
        mid = distance * 4 / 5
        # 计算间隔
        t = 0.2
        # 初速度
        v = 1
        while current < distance:
            if current < mid:
                # 加速度为2
                a = 4
            else:
                # 加速度为-2
                a = -3
            v0 = v
            # 当前速度
            v = v0 + a * t
            # 移动距离
            move = v0 * t + 1 / 2 * a * t * t
            # 当前位移
            current += move
            # 加入轨迹
            track.append(round(move))
        return track
    def save_jingdong_cookie(self):
        self.page.goto("https://passport.shop.jd.com/login/index.action/jdm")
        count = 0
        while count < 100:
            self.page.locator("input[id='loginname']").fill("xxxxxxxxxxxxxxxx")
            self.page.locator("input[placeholder='请输入登录密码']").fill("xxxxxxxxxxxxxxxxxxxxx")
            self.page.wait_for_timeout(1000)
            self.page.locator("button[class='rcd-button rcd-button--primary password__submit']").click()
            self.page.wait_for_timeout(1000)
            # storage = self.context.storage_state(path="auth/state.json")

            self.page.wait_for_timeout(1000)
            bg_src = self.page.locator("//*[@class='JDJRV-bigimg']/img").get_attribute("src")
            # print(bg_src)
            image_base64 = bg_src[22:]
            imgdata = base64.b64decode(image_base64)
            # print(imgdata)
            # 下载图片
            with open(f"../jingdong_order_synchronization_kuaipu_zhuzhanghao/img/bg_src.png", 'wb') as f:
                f.write(imgdata)

            small_src = self.page.locator("//*[@class='JDJRV-smallimg']/img").get_attribute("src")
            image_base64 = small_src[22:]
            imgdata = base64.b64decode(image_base64)
            # print(imgdata)
            # 下载图片
            with open(f"../jingdong_order_synchronization_kuaipu_zhuzhanghao/img/small_src.png", 'wb') as f:
                f.write(imgdata)

            self.page.wait_for_timeout(1000)
            # 图片路径
            bg_path = '../jingdong_order_synchronization_kuaipu_zhuzhanghao/img/bg_src.png'  # 背景图片路径
            slider_path = '../jingdong_order_synchronization_kuaipu_zhuzhanghao/img/small_src.png'  # 滑块图片路径
            distance = self.calculate_slide_distance(bg_path, slider_path)
            s = self.page.wait_for_selector('//*[@class="JDJRV-slide-inner JDJRV-slide-btn"]', strict=True)
            # 找到这个元素再当前页面的坐标（这个会返回一个字典里边四个数字）
            box = s.bounding_box()
            # print(box)
            # 移动鼠标到上边元素的中心（上边四个参数用途来了）
            self.page.mouse.move(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)
            # 按下鼠标（这个不多说）
            self.page.mouse.down()
            # 这里获取到x坐标中心点位置
            x = box["x"] + box["width"] / 2
            # 这个把缺口获取到的长度放到轨迹加工一下得到一个轨迹
            tracks = self.get_track(distance)
            for track in tracks:
                # 循环鼠标按照轨迹移动
                # steps 是控制单次移动速度的比例是1/10 默认是1 相当于 传入的这个距离不管多远0.1秒钟移动完 越大越慢
                self.page.mouse.move(x + track,0)
                x += track
            # 移动结束鼠标抬起
            self.page.mouse.up()

            try:
                time.sleep(3)
                self.page.wait_for_url("https://shop.jd.com/jdm/home")
                time.sleep(5)
            except:
                self.page.reload()


            # if self.page.query_selector("//span[@class='shop-pageframe-header__pin']"):
            if self.page.query_selector("//div[@id='JdmV11Feedback']"):
                cookies = self.context.cookies()
                # print(cookies)
                # 保存 Cookie 到文件
                with open('../jingdong_order_synchronization_kuaipu_zhuzhanghao/auth/jingdong_cookies.json', 'w') as f:
                    json.dump(cookies, f)
                with open('D:/PythonFiles/MyWeb/utils/guotie_jd_price/auth/jingdong_spider_zhuuser_jingdong_cookies.json', 'w') as f:
                    json.dump(cookies, f)
                logs.error("通知程序管理员，COOKIES更新成功。")
                update_cookies_dict_data = {"code": 3,
                                            "status":"success",
                                            "result": "程序即将自动重启",
                                            "update": "已更换京东COOKIES,正在重启"}
                return update_cookies_dict_data
            else:
                # print(self.page.locator("//*[@class='JDJRV-bigimg']/img").get_attribute("src"))
                self.page.reload()
                count += 1
                if count == 100:
                    update_cookies_dict_data = {"code": 3,
                                                "status":"failed",
                                                "result": "程序暂停运行",
                                                "update": "未获取到京东最新COOKIE，需管理员处理后重启！"}
                    return update_cookies_dict_data
                time.sleep(2)

